<template>
    <view class="page-wrapper">
        <!-- 状态栏占位 -->
        <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

        <!-- 顶部导航栏 -->
        <view class="navbar">
            <view class="nav-left" @click="goBack">
                <u-icon name="arrow-left" size="27" color="#fff"></u-icon>
            </view>
            <view class="nav-title">登录</view>
            <!-- <view class="nav-right" @click="goToRegister">注册</view> -->
        </view>

        <view class="login-container">
            <u-form :model="formData" ref="uForm" :rules="rules">
                <u-form-item prop="phone">
                    <u-input v-model="formData.phone" placeholder="请输入手机号" type="number" maxlength="11" border="bottom">
                        <template #prefix>
                            <image src="@/static/img/login/icon-iphone@2x.png" mode="aspectFit"
                                style="height: 39rpx;width: 27rpx; margin-right: 15rpx;margin-left: 11rpx;"></image>
                        </template>
                        <template #suffix>
                            <u-icon name="close-circle" size="27" color="#909399" @click.stop="clearPhone"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <u-form-item v-if="loginType === 'code'" prop="code">
                    <u-input v-model="formData.code" placeholder="请输入短信验证码" type="number" maxlength="6" border="bottom">
                        <template #prefix>
                            <u-icon name="email" size="28" color="#909399"></u-icon>
                        </template>

                        <template #suffix>
                            <u-text text="发送验证码" color="#ff5033" size="14" @click="getCode"
                                :disabled="codeDisabled"></u-text>
                        </template>
                    </u-input>
                </u-form-item>

                <u-form-item v-else prop="password">
                    <u-input v-model="formData.password" placeholder="请输入登录密码"
                        :type="showPassword ? 'text' : 'password'" prefixIcon="lock"
                        prefixIconStyle="font-size: 28px; color: #909399;" border="bottom">
                        <template #suffix>
                            <u-icon :name="showPassword ? 'eye' : 'eye-off'" size="28" color="#909399"
                                @click="togglePassword"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <view class="login-options">
                    <view class="password-login" @click="toggleLoginType" v-if="loginType === 'code'">
                        <u-text text="密码登录" color="#ff5033" size="16"></u-text>
                    </view>
                    <view class="phone-login" v-else>
                        <view class="phone-login-item" @click="toggleLoginType">
                            <text style="color: #ff5033;">短信验证码登录</text>
                        </view>
                        <view class="phone-login-item" @click="goToForget">
                            <text style="color: #ff5033;">忘记密码</text>
                        </view>
                    </view>
                </view>

                <u-button text="立即登录" type="primary" color="#ff5033" :customStyle="{ borderRadius: '10rpx' }"
                    @click="handleLogin"></u-button>
					
					
					 <view class="register-btn" @click="goToRegister">没有账号？  立即注册</view>
            </u-form>

        </view>
        <view class="third-login">
            <view class="third-title">第三方登录</view>
            <WechatPhoneAuth type="icon" text="微信登录" custom-class="wechat-login-btn"
                @success="onWechatLoginSuccess" @error="onWechatLoginError" @register="onWechatRegister"
                @bindPhone="onWechatBindPhone" @h5Login="wechatLogin" />
        </view>
    </view>
</template>

<script>
import api from '@/api/index.js'
import request from '@/api/request.js'
import md5 from 'md5'
import WechatPhoneAuth from '@/components/WechatPhoneAuth/index.vue'
import { saveLoginInfo } from '@/api/auth.js'

export default {
    components: {
        WechatPhoneAuth
    },
    data() {
        return {
            formData: {
                phone: '',
                code: '',
                password: ''
            },
            statusBarHeight: 0,
            loginType: 'code', // code: 验证码登录, password: 密码登录
            showPassword: false, // 是否显示密码
            codeText: '发送验证码', // 验证码按钮文本
            codeDisabled: false, // 验证码按钮是否禁用
            countdown: 60, // 倒计时秒数
            userIp: '0.0.0.0', // 用户IP地址
            latitude: 0, // 纬度
            longitude: 0, // 经度
            rules: {
                phone: [
                    {
                        required: true,
                        message: '请输入手机号',
                        trigger: ['blur', 'change']
                    },
                    {
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入正确的手机号',
                        trigger: ['blur', 'change']
                    }
                ],
                code: [
                    {
                        required: true,
                        message: '请输入验证码',
                        trigger: ['blur', 'change']
                    },
                    {
                        min: 6,
                        max: 6,
                        message: '验证码必须为6位数字',
                        trigger: ['blur', 'change']
                    }
                ],
                password: [
                    {
                        required: true,
                        message: '请输入密码',
                        trigger: ['blur', 'change']
                    },
                    {
                        min: 6,
                        message: '密码不能少于6位',
                        trigger: ['blur', 'change']
                    }
                ]
            }
        }
    },

    onLoad() {
		wx.login({
			success: async (loginRes) => {
				
				if (loginRes.code) {
					const openidResult = await api.wechatApi.getOpenidForMiniProgram({
					  code: loginRes.code
					})
					
				// this.openid = openidResult.data.openid
				uni.setStorageSync('openid',openidResult.data.openid) 
				console.log('获取到openid:', openidResult.data.openid);
				// 显示支付方式选择
				} else {
					uni.showToast({
						title: '获取code失败',
						icon: 'none'
					});
				}
			},
			fail: (error) => {
				
				uni.showToast({
					title: '失败',
					icon: 'none'
				});
			}
		});
		
		
		
        this.getSystemInfo()
        this.getUserIp()
    },
    methods: {
        // 获取系统信息
        getSystemInfo() {
            const systemInfo = uni.getSystemInfoSync()
            this.statusBarHeight = systemInfo.statusBarHeight || 0
        },

        // 返回上一页
        goBack() {
            uni.navigateBack()
        },

        // 获取验证码
        async getCode() {
            if (this.codeDisabled) {
                return
            }

            if (!this.formData.phone) {
                uni.showToast({
                    title: '请输入手机号',
                    icon: 'none'
                })
                return
            }

            if (!this.validatePhone(this.formData.phone)) {
                uni.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                })
                return
            }

            try {
                // 显示加载中
                uni.showLoading({
                    title: '发送中...'
                })

                // 1. 获取IP地址
                const ipRes = await this.getUserIp()
                if (!ipRes.success) {
                    uni.hideLoading()
                    uni.showToast({
                        title: ipRes.message || '获取IP失败',
                        icon: 'none'
                    })
                    return
                }

                // 2. 检查手机号是否已注册
                const checkRes = await this.checkMobile(this.formData.phone)
                if (!checkRes.success) {
                    uni.hideLoading()
                    uni.showToast({
                        title: checkRes.message || '手机号验证失败',
                        icon: 'none'
                    })
                    return
                }

                // 3. 发送验证码
                const codeRes = await this.sendVerifyCode(this.formData.phone)
                uni.hideLoading()

                if (codeRes.success) {
                    // 开始倒计时
                    this.startCountdown()
                    uni.showToast({
                        title: '验证码已发送',
                        icon: 'success'
                    })
                } else {
                    uni.showToast({
                        title: codeRes.message || '发送失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                uni.hideLoading()
                console.error('发送验证码失败:', error)
                uni.showToast({
                    title: '发送失败，请重试',
                    icon: 'none'
                })
            }
        },

        // 开始倒计时
        startCountdown() {
            this.codeDisabled = true
            this.countdown = 60
            this.codeText = `重新发送(${this.countdown})`

            const timer = setInterval(() => {
                this.countdown--
                if (this.countdown <= 0) {
                    clearInterval(timer)
                    this.codeDisabled = false
                    this.codeText = '发送验证码'
                } else {
                    this.codeText = `重新发送(${this.countdown})`
                }
            }, 1000)
        },

        // 切换登录方式
        toggleLoginType() {
            this.loginType = this.loginType === 'code' ? 'password' : 'code'
        },

        clearPhone() {
            console.log('clearPhone clicked');
            this.formData.phone = '';
            // 清空后重置表单校验状态
            this.$nextTick(() => {
                if (this.$refs.uForm) {
                    this.$refs.uForm.clearValidate('phone');
                }
            });
        },


        // 切换密码显示状态
        togglePassword() {
            this.showPassword = !this.showPassword
        },

        // 验证手机号格式
        validatePhone(phone) {
            const phoneReg = /^1[3-9]\d{9}$/
            return phoneReg.test(phone)
        },

        async handleLogin() {
            try {
                // 使用uview-plus表单验证
                const valid = await this.$refs.uForm.validate()
                if (!valid) {
                    return
                }

                // 显示加载中
                uni.showLoading({
                    title: '登录中...'
                })

                let result
                if (this.loginType === 'code') {
                    // 短信验证码登录
                    result = await api.authApi.login({
                        un: this.formData.phone,
                        pwd: md5(this.formData.code),
                        code: this.formData.code,
                        last_login_ip: this.userIp,
                        type: 1,
                        salt: '1234',
                        latitude: this.latitude || 0,
                        longitude: this.longitude || 0,
                        mobile: this.formData.phone
                    })
                } else {
                    // 密码登录
                    result = await api.authApi.login({
                        un: this.formData.phone,
                        pwd: md5(this.formData.password),
                        last_login_ip: this.userIp,
                        type: 2,
                        salt: '1234',
                        latitude: this.latitude || 0,
                        longitude: this.longitude || 0,
                        mobile: this.formData.phone
                    })
                }

                uni.hideLoading()

                if (result.r === 0) {
                    // 登录成功，保存用户信息到缓存
                    const userInfo = result.data
                    saveLoginInfo(userInfo, userInfo.token)

                    uni.showToast({
                        title: '登录成功',
                        icon: 'success'
                    })

                    // 跳转到首页
                    setTimeout(() => {
                        uni.reLaunch({
                            url: '/pages/index/index'
                        })
                    }, 800)
                } else {
                    uni.showToast({
                        title: result.msg || '登录失败',
                        icon: 'none'
                    })
                }

                console.log('登录', {
                    phone: this.formData.phone,
                    code: this.formData.code,
                    password: this.formData.password,
                    loginType: this.loginType
                })
            } catch (error) {
                uni.hideLoading()
                console.log('表单验证失败或登录异常:', error)
                uni.showToast({
                    title: '网络异常，请重试',
                    icon: 'none'
                })
            }
        },


        // 微信登录（非小程序环境使用）
        wechatLogin() {
            // #ifndef MP-WEIXIN
            uni.showToast({
                title: '请在微信小程序中使用',
                icon: 'none'
            })
            // #endif
        },


        goToRegister() {
            uni.navigateTo({
                url: '/pages/login/register'
            })
        },

        goToForget() {
            uni.navigateTo({
                url: '/pages/login/forget'
            })
        },

        // 获取用户IP地址
        async getUserIp() {
            try {
                const result = await request.request({
                    url: 'wap/wx_help/getip',
                    datas: {},
                    showLog: false
                });
                console.log('获取IP结果:', result);
                if (result.r === 0) {
                    this.userIp = result.data;
                    console.log('用户IP:', this.userIp);
                    return { success: true, ip: result.data };
                } else {
                    return { success: false, message: result.msg || '获取IP失败' };
                }
            } catch (error) {
                console.error('获取IP失败:', error);
                return { success: false, message: '网络异常' };
            }
        },

        // 检查手机号是否已注册
        async checkMobile(mobile) {
            try {
                const result = await api.authApi.checkMobile({
                    phone: mobile
                });
                console.log('检查手机号结果:', result);

                if (result.r === 0) {
                    if (result.data.is_used === 1) {
                        return { success: true };
                    } else {
                        return { success: false, message: '手机号未注册，请先注册' };
                    }
                } else {
                    return { success: false, message: result.msg || '检查手机号失败' };
                }
            } catch (error) {
                console.error('检查手机号失败:', error);
                return { success: false, message: '网络异常，请重试' };
            }
        },

        // 发送验证码
        async sendVerifyCode(mobile) {
            try {
                const result = await api.userApi.sendCode({
                    mobile: mobile
                });
                console.log('发送验证码结果:', result);

                if (result.r === 0) {
                    return { success: true, message: result.msg || '验证码已发送' };
                } else {
                    return { success: false, message: result.msg || '发送失败' };
                }
            } catch (error) {
                console.error('发送验证码失败:', error);
                return { success: false, message: '网络异常，请重试' };
            }
        },

        // ====== 新的微信登录事件处理方法 ======
        // 微信登录成功
        onWechatLoginSuccess(userInfo) {
            console.log('微信登录成功:', userInfo)
            // 直接跳转，无需提示
            uni.reLaunch({
                url: '/pages/index/index'
            })
        },

        // 微信登录失败
        onWechatLoginError(error) {
            console.error('微信登录失败:', error)
            uni.showToast({
                title: error || '登录失败，请重试',
                icon: 'none'
            })
        },

        // 微信登录需要注册 - 自动注册
        async onWechatRegister(registerData) {
            console.log('需要注册，开始自动注册:', registerData)

            try {
                uni.showLoading({ title: '注册中...' })

                // 自动调用注册接口
                const registerResult = await api.userApi.register({
                    mobile: registerData.mobile,
                    pwd: '', // 微信注册不需要密码
                    invite_code: uni.getStorageSync('invite_code') || '',
                    region: 0,
                    login_ip: this.userIp,
                    salt: '1234',
                    type: 4, // 微信注册
                    longitude: this.longitude,
                    latitude: this.latitude,
                    unionid: registerData.unionid,
                    openid: registerData.openid,
                    nickname: '',
                    headimgurl: '',
                    sex: 0
                })

                uni.hideLoading()

                if (registerResult.r === 0) {
                    // 注册成功，保存用户信息
                    saveLoginInfo(registerResult.data, registerResult.data.token)

                    // 直接跳转，无需提示
                    uni.reLaunch({
                        url: '/pages/index/index'
                    })
                } else {
                    uni.showToast({
                        title: registerResult.msg || '注册失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                uni.hideLoading()
                console.error('自动注册失败:', error)
                uni.showToast({
                    title: '注册失败，请重试',
                    icon: 'none'
                })
            }
        },

        // 微信登录需要绑定手机号
        onWechatBindPhone(bindData) {
            console.log('需要绑定手机号:', bindData)
            uni.navigateTo({
                url: `/pages/login/phone_bind?openid=${bindData.openid}&unionid=${bindData.unionid}`
            })
        }
    }
}
</script>

<style scoped>
/* 页面整体布局 */
.page-wrapper {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: #f5f5f5;
}

/* 状态栏和导航栏 */
.status-bar,
.navbar {
    background: #ff5033;
}

.navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.nav-title {
    font-weight: bold;
    flex: 1;
}

/* 登录选项 */
.phone-login {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}

.phone-login-item {
    cursor: pointer;
    padding: 8rpx 0;
}

/* 第三方登录 */
.third-login {
    text-align: center;
}

.third-icons {
    display: flex;
    justify-content: center;
}

.wechat-icon {
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 微信授权按钮样式 - 让 button 看起来像普通图标 */
.phone-auth-btn {
    padding: 0;
    margin: 0;
    border: none;
    background: transparent;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

.phone-auth-btn::after {
    border: none;
}



/* 导航栏详细样式 */
.status-bar {
    width: 100%;
}

.navbar {
    height: 88rpx;
    padding: 0 185rpx 0 40rpx;
    color: white;
}

.nav-title {
    font-size: 36rpx;
    text-align: center;
}

.nav-right {
    text-align: right;
    font-size: 32rpx;
    font-weight: bold;
    white-space: nowrap;
    flex-shrink: 0;
}

.register-btn {
    text-align: center;
    font-size: 32rpx;
    white-space: nowrap;
	margin-top: 20rpx;
    flex-shrink: 0;
}

/* 登录表单 */
.login-container {
    padding: 100rpx 50rpx;
    background: #fff;
    border-radius: 20rpx;
    margin: 100rpx 40rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

/* 表单项间距 */
.login-container /deep/ .u-form-item {
    margin-bottom: 20rpx;
}

.login-options {
    margin: 40rpx 0 30rpx 0;
    padding: 0 10rpx;
}

.password-login {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 8rpx 0;
}

/* 第三方登录 */
.third-login {
    margin-top: 80rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.third-title {
    color: #999;
    font-size: 28rpx;
    margin-bottom: 40rpx;
    display: flex;
    align-items: center;
    padding: 0 40rpx;
    width: 100%;
}

.third-title::before,
.third-title::after {
    content: '';
    flex: 1;
    height: 1rpx;
    background: #d8d8d8;
    margin: 0 30rpx;
}

.third-icons {
    margin-bottom: 20rpx;
}

.wechat-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    box-shadow: 0 4rpx 12rpx rgba(26, 173, 25, 0.3);
}

.wechat-text {
    color: #666;
    font-size: 26rpx;
    margin-top: 16rpx;
}

/* 微信登录按钮居中 */
.wechat-login-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
</style>